package com.sudo.demo.security.handler;

import com.demo.common.base.pojo.JsonRes;
import com.sudo.demo.security.util.GsonUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证失败处理器
 * AuthenticationFailureHandler 用来解决身份验证失败的异常(适用表单登录方式)
 *
 * @author zhaoxg on 2023年04月18日 10:15
 */
//public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        // 认证失败状态码 401
        // 当认证成功后，响应 JSON 数据给前端
        response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);
        JsonRes<Object> jsonRes = JsonRes.error(401,"认证失败");
        String json = GsonUtil.simpleObjToJson(jsonRes);
        response.getWriter().write(json);
    }
}
